
var area = require('../../../utils/area.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId:null,
    avatarUrl: "",
    openid: "",

    phone: "",
    name: "",
    idCard: "",
    sex: null,
    address: "",
    houseInfo: "",

    phoneError: "",
    nameError: "",
    idCardError: "",
    houseInfoError: "",

    areaShow: false,
    selectAreaCode: "441900",
    areaList: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = getApp().globalData.userInfo;
    this.setData({
      areaList: area.default,
      userId:userInfo.userId,
      avatarUrl: userInfo.avatarUrl,
      openid: userInfo.openid,
      phone: userInfo.phone,
      name: userInfo.name,
      idCard: userInfo.idCard,
      sex: userInfo.sex + "",
      address: userInfo.address,
      houseInfo: userInfo.houseInfo
    });
  },
  submitInfo() {
    //检查修改信息是否有误
    if (this.data.phoneError != "" || this.data.nameError != "" ||
      // this.data.passwordError != "" || this.data.confirmPasswordError != "" ||
      this.data.idCardError != "" || this.data.houseInfoError != "") {
      wx.showToast({
        title: '修改信息有误，请检查一下',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    //检查修改信息是否为空
    if (this.data.phone == "" ||
    //  this.data.password == "" ||
      this.data.name == "" || this.data.idCard == "" || this.data.sex == null ||
      this.data.address == "" || this.data.houseInfo == "") {
      wx.showToast({
        title: '修改信息不能为空，请检查一下',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    
    //如果修改了头像，才上传头像
    let that = this;
    if(this.data.avatarUrl != getApp().globalData.userInfo.avatarUrl){
      //上传图片
      wx.uploadFile({
        url: getApp().globalData.BASE_URL + '/common/upload/avatar',
        filePath: this.data.avatarUrl,
        name: 'file',
        formData: {
          userId: getApp().globalData.userInfo.userId
        },
        header: {
          'Authorization': getApp().globalData.TOKEN
        },
        success(res) {
          // console.log(res.data)
          let result = JSON.parse(res.data)
          if (result.code==200){
            that.setData({
              avatarUrl: result.msg
            })
            that.updateUserInfo();
          }else{
            wx.showToast({
              title: '头像上传失败！' + result.msg,
              icon: 'none',
              duration: 2000
            });
          }
        }
      })
    }else{
      this.updateUserInfo();
    }
  },


  updateUserInfo(){
    //提交修改信息
    wx.request({
      url: getApp().globalData.BASE_URL + "/user",
      method: "put",
      data: {
        userId: getApp().globalData.userInfo.userId,
        avatarUrl: this.data.avatarUrl,
        openid: this.data.openid,
        name: this.data.name,
        phone: this.data.phone,
        idCard: this.data.idCard,
        sex: this.data.sex,
        address: this.data.address,
        houseInfo: this.data.houseInfo
      },
      header: {
        'content-type': 'application/json',
        'Authorization': getApp().globalData.TOKEN
      },
      success(res) {
        if (res.data.code == 200) {
          console.log("更新用户信息成功")
          //更新登录信息
          wx.request({
            url: getApp().globalData.BASE_URL + "/update/userInfo",
            method: "POST",
            data: {},
            header: {
              'content-type': 'application/json',
              'Authorization': getApp().globalData.TOKEN
            },
            success(resp) {
              if (resp.data.code == 200) {
                console.log("更新登录信息成功")
                wx.showToast({
                  title: '修改成功！',
                  duration: 1500
                });
                getApp().globalData.userInfo = resp.data.data
              } else {
                wx.showToast({
                  title: resp.data.msg,
                  icon: 'none',
                  duration: 1500
                });
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1500
          });
        }
      }
    })
  },

  //切换头像
  changeAvatar: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var path = res.tempFilePaths[0];
        that.setData({
          avatarUrl: path
        })
      }
    })
  },

  checkPhone(e) {
    let value = e.detail.value;
    let message = "";
    var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
    if (value == '') {
      message = "手机号码不能为空！";
    } else if (value.length != 11) {
      message = "请输入11位手机号码！";
    } else if (!myreg.test(value)) {
      message = "请输入有效的手机号码！";
    } else {
      let _this = this;
      //查询后台该手机号是否被注册
      wx.request({
        url: getApp().globalData.BASE_URL + "/user/phone/judge",
        method: "GET",
        data: {
          phone: value,
          userId: _this.data.userId
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data.code === 200 && res.data.data === false) {
            message = "该号码已经被注册拥有";
            _this.setData({
              phoneError: message
            })
          }
        }
      })
    }
    this.setData({
      phoneError: message
    })
  },
  // checkPassword(e) {
  //   let value = e.detail.value;
  //   if (value == "") {
  //     this.setData({
  //       passwordError: "密码不能为空"
  //     })
  //   } else {
  //     this.setData({
  //       passwordError: ""
  //     })
  //   }
  // },
  // checkConfirmPassword(e) {
  //   let value = e.detail.value;
  //   if (value != this.data.password) {
  //     this.setData({
  //       confirmPasswordError: "两次密码输入不一致！"
  //     })
  //   } else {
  //     this.setData({
  //       confirmPasswordError: ""
  //     })
  //   }
  // },
  checkName(e) {
    let value = e.detail.value;
    if (value == "") {
      this.setData({
        nameError: "姓名不能为空"
      })
    } else {
      this.setData({
        nameError: ""
      })
    }
  },
  checkIdCard(e) {
    let value = e.detail.value;
    if (value == "") {
      this.setData({
        idCardError: "身份证号不能为空"
      })
    } else if (value.length != 18) {
      this.setData({
        idCardError: "请输入18位身份证号"
      })
    } else {
      this.setData({
        idCardError: ""
      })
    }
  },
  checkHouseInfo(e) {
    let value = e.detail.value;
    if (value == "") {
      this.setData({
        houseInfoError: "详细地址不能为空"
      })
    } else {
      this.setData({
        houseInfoError: ""
      })
    }
  },
  changePhone(event) {
    this.setData({
      phone: event.detail,
    });
  },
  // changePassword(event) {
  //   this.setData({
  //     password: event.detail,
  //   });
  // },
  changeName(event) {
    this.setData({
      name: event.detail,
    });
  },
  changeIdCard(event) {
    this.setData({
      idCard: event.detail,
    });
  },
  onChangeSex(event) {
    this.setData({
      sex: event.detail,
    });
  },
  onChangeDetailedAddress(event) {
    this.setData({
      houseInfo: event.detail
    })
  },
  onClickAreaIcon() {
    this.setData({
      areaShow: true
    });
  },
  onCancelArea() {
    this.setData({
      areaShow: false
    });
  },
  onSelectArea(event) {
    console.log(event.detail.values[2].code)
    let selectArea = event.detail.values[0].name + event.detail.values[1].name + event.detail.values[2].name;
    this.setData({
      areaShow: false,
      selectAreaCode: event.detail.values[2].code.code,
      address: selectArea
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})